import { Button, Card, List, message, Modal, Result, Typography } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import Search from 'antd/es/input/Search';
import { delChart, listCharts } from '@/services/ant-design-pro/api';
import ReactECharts from 'echarts-for-react';
import { DeleteOutlined, DownloadOutlined, RedoOutlined } from '@ant-design/icons';

const { Paragraph } = Typography;

/**
 * 我的图表页面
 * @constructor
 */
const MyChartPage: React.FC = () => {
  const initSearchParams = {
    pageNum: 1,
    pageSize: 4,
    chartName: '',
  };

  const [searchValue, setSearchValue] = useState('');
  const [searchParams, setSearchParams] = useState<API.ListChartsParams>({ ...initSearchParams });
  const [chartList, setChartList] = useState<API.Chart[]>([]);
  const [total, setTotal] = useState<number>(0);
  const [loading, setLoading] = useState<boolean>(true);

  const chartRefs = useRef<ReactECharts[]>([]); // 存储多个图表的 refs

  const loadData = async () => {
    setLoading(true);
    try {
      const res = await listCharts(searchParams);
      if (res.data) {
        if (res.data.list) {
          res.data.list.forEach((data: { resultChart: string }) => {
            let chartOption = null;
            try {
              chartOption = JSON.parse(data.resultChart ?? '{}');
              chartOption.title = undefined;
            } catch (e) {
              chartOption = {
                title: {
                  text: '图表样式解析失败，可尝试重新生成',
                  left: 'center',
                  textStyle: {
                    color: '#1890FF',
                  },
                },
              };
            }
            data.resultChart = JSON.stringify(chartOption);
          });
        }
        setChartList(res.data.list ?? []);
        setTotal(res.data.total ?? 0);
      } else {
        message.error('获取我的图表失败');
      }
    } catch (e: any) {
      message.error('获取我的图表失败，' + e.message);
      console.error('获取我的图表失败，', e.message);
    }
    setLoading(false);
  };

  const onSearch = (value: string) => {
    setLoading(true);
    setSearchValue(value);
    setSearchParams({
      ...initSearchParams,
      chartName: value,
    });
    setLoading(false);
  };

  const onReset = () => {
    setSearchValue('');
    setSearchParams({ ...initSearchParams });
  };

  const handleRemove = (id: number) => {
    Modal.confirm({
      content: '删除后无法恢复，确认删除？',
      onOk: async () => {
        try {
          const res = await delChart({ id: id });
          if (res.code === 0) {
            message.success('删除成功');
            loadData();
          } else {
            message.error('删除失败，' + res.message);
          }
        } catch (e: any) {
          message.error('删除失败，' + e.message);
        }
      },
    });
  };

  const downloadImage = (name: string, index: number) => {
    const chartInstance = chartRefs.current[index].getEchartsInstance();
    const dataURL = chartInstance.getDataURL({
      type: 'png',
      pixelRatio: 5,
    });

    const link = document.createElement('a');
    link.href = dataURL;
    link.download = name ? `${name}.png` : 'favicon.ico';
    link.click();
  };

  useEffect(() => {
    loadData();
  }, [searchParams]);

  // @ts-ignore
  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
        <Button
          style={{ marginRight: 13 }}
          type="primary"
          icon={<RedoOutlined />}
          loading={loading}
          onClick={() => onReset()}
        />
        <Search
          value={searchValue}
          placeholder="输入图表名称"
          enterButton
          loading={loading}
          onChange={(e) => setSearchValue(e.target.value)}
          onSearch={(value) => onSearch(value)}
        />
      </div>
      <div style={{ marginTop: 16 }} />
      <List
        grid={{
          gutter: 16,
          xs: 1,
          sm: 1,
          md: 1,
          lg: 2,
          xl: 2,
          xxl: 2,
        }}
        pagination={{
          onChange: (page, pageSize) => {
            setSearchParams({
              ...searchParams,
              pageNum: page,
              pageSize,
            });
          },
          showTotal: () => `共 ${total} 条`,
          current: searchParams.pageNum,
          pageSize: searchParams.pageSize,
          total: total,
        }}
        loading={loading}
        dataSource={chartList}
        renderItem={(item, index) => (
          <List.Item key={item.id}>
            <Card
              style={{ width: '100%' }}
              title={item.chartName}
              extra={<DeleteOutlined onClick={() => handleRemove(item.id)} />}
            >
              <List.Item.Meta title={'分析诉求：' + item.goal} description={item.createTime} />
              <>
                {item.status === 0 && (
                  <Result
                    status="warning"
                    title="待生成"
                    subTitle={item.genLog ?? '当前图表生成队列繁忙，请耐心等候'}
                  />
                )}
                {item.status === 1 && (
                  <Result status="info" title="图表生成中" subTitle={item.genLog} />
                )}
                {item.status === 2 && (
                  <>
                    <DownloadOutlined
                      onClick={() => downloadImage(item.chartName, index)} // 传递当前图表的索引
                      style={{ float: 'right' }}
                    />
                    <div style={{ marginBottom: 16 }} />
                    <ReactECharts
                      ref={(el) => (chartRefs.current[index] = el)} // 存储当前图表的 ref
                      option={item.resultChart && JSON.parse(item.resultChart)}
                    />
                    <div style={{ marginBottom: 16 }} />
                    <Paragraph copyable>{'分析结论：' + item.resultText}</Paragraph>
                  </>
                )}
                {item.status === 3 && (
                  <Result status="error" title="图表生成失败" subTitle={item.genLog} />
                )}
              </>
            </Card>
          </List.Item>
        )}
      />
    </div>
  );
};

export default MyChartPage;
